import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:hc_bio_sdk/hc_bio_sdk.dart';
import 'package:hc_bio_sdk/model/heart_rate.dart';
import 'package:hc_bio_sdk/model/hrv.dart';
import 'package:hc_bio_sdk/model/main_Indicator.dart';
import 'package:hc_bio_sdk/model/mind_read_result.dart';
import 'package:hc_bio_sdk/model/rr.dart';
import 'package:hc_bio_sdk/model/wave.dart';

class BioController extends GetxController {
  final _sdk = HcBioSdk();

  BioController();

  _initData() {
    update(["bio"]);

    _sdk.dataStream.listen((event) {
      if (event is HRV) {
        debugPrint("got hrv: $event");
      } else if (event is HeartRate) {
        debugPrint("got HeartRate: $event");
      } else if (event is MainIndicator) {
        debugPrint("got MainIndicator: $event");
      } else if (event is Wave) {
        debugPrint("got wave: $event");
      } else if (event is MindReadResult) {
        debugPrint("got MindReadResult: $event");
      }
    });
  }

  void onTap() {
    makeBio();
  }

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}

extension on BioController {
  Future makeBio() async {
    final rrDataStr = await rootBundle.loadString("assets/20250411162136.txt");
    final entries = rrDataStr.split("\r\n");
    entries.removeWhere((e) => e.trim().isEmpty);
    final rrData = entries.map((e) {
      final dataSlice = e.split(",");
      final timestamp = int.parse(dataSlice[0]);
      final rr = int.parse(dataSlice[1]);
      return RRModel(rr: rr, timestamp: timestamp);
    }).toList();
    appendRR(rrData);
  }

  Future appendRR(List<RRModel> rrList) async {
    for (var e in rrList) {
      await _sdk.append(e);
      await Future.delayed(Duration(milliseconds: 10));
    }
  }
}
